//
//  WeekendController.m
//  隐藏导航条-04
//
//  Created by key on 16/4/19.
//  Copyright © 2016年 key. All rights reserved.
//

#import "SIXUserInfoViewController.h"
#import "UIImage+Image.h"
#import "SIXMeTableController.h"
#import "SIXBasicTableViewController.h"
#import "SIXNavigationController.h"
#import "SIXMeModels.h"
#import "SIXSearchTableViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kHeaderH 250
#define kBar 44
#define kNavBarBackgroundH 64
CGFloat const XMGTitilesViewH = 35;
/** 精华-顶部标题的Y */
CGFloat const XMGTitilesViewY = 64;
@interface SIXUserInfoViewController()<SIXMeTableController,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerHCons;
@property (weak, nonatomic) IBOutlet UIImageView *avatorImage;
@property (weak, nonatomic) IBOutlet UIButton *editUserInfo;
@property (weak, nonatomic) IBOutlet UIView *avatorView;
@property (weak, nonatomic) IBOutlet UIView *userMenuView;
@property (weak, nonatomic) IBOutlet UILabel *nameLable;
@property (strong,nonatomic)SIXMeModels *model;
/** 标签栏底部的红色指示器 */
@property (nonatomic, weak) UIView *indicatorView;
/** 当前选中的按钮 */
@property (nonatomic, weak) UIButton *selectedButton;
/** 顶部的所有标签 */
@property (nonatomic, weak) UIView *titlesView;

/**titleLabel*/
@property(weak,nonatomic)UILabel *titleLabel;
/**偏移量*/
@property(assign,nonatomic)CGFloat defOffSetY;
/** 底部的所有内容 */
@property (nonatomic, weak) UIScrollView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *guanzhu;
@property (weak, nonatomic) IBOutlet UILabel *fensi;

@property (nonatomic,weak)UILabel *navLabel;

@end

@implementation SIXUserInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化配置
    [self setUp];
    //配置个人微博信息
    [self setUserInfo];
    //设置子控制器
    [self setupChildVces];
    //设置标签栏
    [self setupTitlesView];
    
    //设置底部滚动区域
    [self setupContentView];
    
    [self.view bringSubviewToFront:self.avatorView];
    [self.view bringSubviewToFront:self.userMenuView];
    
}
- (void)setUserInfo{
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"SIXMe" ofType:@"plist"]];
    SIXMeModels *models = [SIXMeModels modelsWithDict:dict];

    [self.avatorImage.image circleImage];
    [self.avatorImage sd_setImageWithURL:[NSURL URLWithString:models.userIcon]];
    self.nameLable.text = models.userName;
    self.fensi.text = models.fansCount;
    self.guanzhu.text = models.focusCount;
    self.model = models;
}

#pragma mark -- 设置底部滚动的内容

/**
 * 初始化子控制器
 */
- (void)setupChildVces
{
    SIXMeTableController *home = [[SIXMeTableController alloc] init];
    home.title = @"主页";
    home.type = SIXUserHomeType;
    //设置tableView额外滚动区域为kHeaderH+kBar(两个的高度和)
    home.tableView.contentInset = UIEdgeInsetsMake(kHeaderH+kBar, 0, 0, 0);
    home.view.backgroundColor = [UIColor grayColor];
    home.delegate = self;
    [self.view addSubview:home.tableView];
    [self addChildViewController:home];
    
    
    SIXMeTableController *weibo = [[SIXMeTableController alloc] init];
    weibo.title = @"微博";
    weibo.type = SIXUserWeiboType;
    weibo.tableView.contentInset = UIEdgeInsetsMake(kHeaderH+kBar, 0, 0, 0);
    weibo.delegate =self;
    weibo.view.backgroundColor = [UIColor grayColor];
    [self.view addSubview:weibo.tableView];
    [self addChildViewController:weibo];
    
    
    SIXMeTableController *photo = [[SIXMeTableController alloc] init];
    photo.title = @"相册";
    photo.type = SIXUserPhotoType;
    photo.tableView.contentInset = UIEdgeInsetsMake(kHeaderH+kBar, 0, 0, 0);
    photo.delegate = self;
    photo.view.backgroundColor =[UIColor redColor];
    [self.view addSubview:photo.tableView];
    [self addChildViewController:photo];
    

}
/**
 * 设置顶部的标签栏
 */
- (void)setupTitlesView
{
    // 标签栏整体
    UIView *titlesView = [[UIView alloc] init];
    titlesView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
    titlesView.width = self.view.width;
    titlesView.height = XMGTitilesViewH;
    titlesView.y =0;
    [self.userMenuView addSubview:titlesView];
    self.titlesView = titlesView;
    
    
    // 底部的红色指示器
    UIView *indicatorView = [[UIView alloc] init];
    indicatorView.backgroundColor = [UIColor orangeColor];
    indicatorView.height = 2;
    indicatorView.tag = -1;
    indicatorView.y = titlesView.height - indicatorView.height;
    self.indicatorView = indicatorView;
    
    // 内部的子标签
    CGFloat width = titlesView.width / self.childViewControllers.count;
    CGFloat height = titlesView.height;
    for (NSInteger i = 0; i<self.childViewControllers.count; i++) {
        UIButton *button = [[UIButton alloc] init];
        button.tag = i;
        button.height = height;
        button.width = width;
        button.x = i * width;
        UIViewController *vc = self.childViewControllers[i];
        [button setTitle:vc.title forState:UIControlStateNormal];
        //      [button layoutIfNeeded]; // 强制布局(强制更新子控件的frame)
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateDisabled];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        [titlesView addSubview:button];
        
        // 默认点击了第一个按钮
        if (i == 0) {
            button.enabled = NO;
            self.selectedButton = button;
            
            // 让按钮内部的label根据文字内容来计算尺寸
            [button.titleLabel sizeToFit];
            self.indicatorView.width = button.titleLabel.width;
            self.indicatorView.centerX = button.centerX;
        }
    }
    
    [titlesView addSubview:indicatorView];
}

- (void)titleClick:(UIButton *)button
{
    // 修改按钮状态
    self.selectedButton.enabled = YES;
    button.enabled = NO;
    self.selectedButton = button;
    
    // 动画
    [UIView animateWithDuration:0.25 animations:^{
        self.indicatorView.width = button.titleLabel.width;
        self.indicatorView.centerX = button.centerX;
    }];
    
    // 滚动
    CGPoint offset = self.contentView.contentOffset;
    offset.x = button.tag * self.contentView.width;
    [self.contentView setContentOffset:offset animated:YES];
}


/**
 * 底部的scrollView
 */
- (void)setupContentView
{
    // 不要自动调整inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIScrollView *contentView = [[UIScrollView alloc] init];
    contentView.frame = self.view.bounds;
    contentView.delegate = self;
    contentView.pagingEnabled = YES;
    [self.view insertSubview:contentView atIndex:0];
    contentView.contentSize = CGSizeMake(contentView.width * self.childViewControllers.count, 0);
    self.contentView = contentView;
    
    // 添加第一个控制器的view
    [self scrollViewDidEndScrollingAnimation:contentView];
}
#pragma mark -- 设置scroller滚动<UIScrollViewDelegate>
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 当前的索引
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    //NSLog(@"----%ld",index);
    // 取出子控制器
    UIViewController *vc = self.childViewControllers[index];
    vc.view.x = scrollView.contentOffset.x;
    vc.view.y = 0; // 设置控制器view的y值为0(默认是20)
    vc.view.height = scrollView.height; // 设置控制器view的height值为整个屏幕的高度(默认是比屏幕高度少个20)
    [scrollView addSubview:vc.view];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewDidEndScrollingAnimation:scrollView];
    
    // 点击按钮
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    [self titleClick:self.titlesView.subviews[index]];
}


#pragma mark -- 设置导航和其他配置
- (void)setUp{
    
    self.view.backgroundColor = [UIColor orangeColor];
    /**
     *  记录初始偏移量一定要在设置额外滚动区域之前
     因为一旦设置额外滚动区域后,系统会自动跳到scrollViewDidScroll:这个代理方法中去
     这样在scrollViewDidScroll:就不会获得已经记录了的初始偏移量
     */
    
    //记录程序启动完成时的偏移量
    self.defOffSetY = -(kHeaderH+kBar);
    

    //ios7 之后当scrollView添加到导航控制器中,会默认设置有额外的滚动区域
    //去除默认滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
    //让导航控制器的导航条隐藏(其实就是隐藏背景图片)
    [self setUpNavBar];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UIBarButtonItem *leftBtn =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    
    self.navigationItem.leftBarButtonItem = leftBtn;
    
    UIBarButtonItem *rightBtn =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tabbar_discover"] style:UIBarButtonItemStyleDone target:self action:@selector(search)];
    
    self.navigationItem.rightBarButtonItem = rightBtn;

}
- (void)search{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MessageSearch" bundle:nil];
        SIXSearchTableViewController *searchVC = [storyboard instantiateInitialViewController];
        
        [self presentViewController:searchVC animated:YES completion:nil];

}

- (void)back{
    NSLog(@"返回");
    self.navigationController.navigationBar.frame = CGRectMake(0, 0, self.view.width, 64);
    //self.defOffSetY = (kHeaderH+kBar);
    //设置tableView额外滚动区域为kHeaderH+kBar(两个的高度和)
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tiaozhuan" object:nil];
    
    UIColor *navBackground = [UIColor colorWithRed:0.926 green:0.911 blue:0.860 alpha:1.000];;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:navBackground] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController popToRootViewControllerAnimated:YES];
}


#pragma mark - 接收tableView滚动的通知，并传递偏移量过来
- (void)SIXMeTableControllerOffsetY:(CGFloat)offsetY{
    [self tableViewScroll:offsetY];
}

-(void)tableViewScroll:(CGFloat)offSetY{
    //导航栏标题
    NSString *name = self.model.userName;
    UILabel *label = [[UILabel alloc]init];
    label.textColor = [UIColor whiteColor];
    label.text = [NSString stringWithFormat:@"%@",name];
    label.frame = CGRectMake(0, 0, 80, 40);
    label.textAlignment = NSTextAlignmentCenter;
    self.navLabel = label;
    self.navigationItem.titleView = label;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //求出滚动时的偏移量
    //CGFloat offSetY = scrollView.contentOffset.y;
    //偏移量变化值 = 用实际的偏移量 - 初始偏移量
    CGFloat delta = offSetY-self.defOffSetY;
    NSLog(@"------%f",delta);
    /**
        这里取出headerView的高度约束
     *  当tableView往上滚动的时候,让headerView的高度减少delta
        往上滚动时headerView的高度不断减少,当headerView的高度<=导航条的背景高度
        让headerView的高度==导航条的背景高度
     */
    
    //当tableView往上滚动的时候,让headerView的高度减少delta
    CGFloat headerViewH = kHeaderH-delta;
    //往上滚动时headerView的高度不断减少,当headerView的高度<=导航条的背景高度
   // 让headerView的高度==导航条的背景高度
    if (headerViewH<kNavBarBackgroundH) {
        headerViewH = kNavBarBackgroundH;
    }
    self.headerHCons.constant = headerViewH;
    
    //让透明度随着headerView的高度变化而变化
    CGFloat alpha = delta/(kHeaderH-kNavBarBackgroundH);
    
    if (alpha>1) {
        alpha=0.99;
        
    }
    
    //根据alpha让titleLabel显示和隐藏
    self.titleLabel.textColor = [UIColor colorWithWhite:0 alpha:alpha];
    //根据alpha让导航栏背景显示和隐藏,这里运用了image一个分类的方法使颜色变成图片
    UIColor *navBackground = [UIColor colorWithRed:0.926 green:0.911 blue:0.860 alpha:alpha];
    //self.navigationController.navigationBar.tintColor = [[UIColor whiteColor] colorWithAlphaComponent:alpha];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:navBackground] forBarMetrics:UIBarMetricsDefault];
    
    self.navigationItem.titleView.alpha = alpha;
    //当达到某一定透明度后，标题就变为黑色
    if (alpha>0.8) {
       // self.titleLabel.textColor = [UIColor blackColor];
        self.navigationController.navigationBar.tintColor = [UIColor blackColor];
        self.navLabel.textColor = [UIColor blackColor];
    }
    
}

-(void)setUpNavBar{
    
    UIImage *image = [[UIImage alloc] init];
    /**
     *  导航控制器默认高度为44
        我们看到导航控制器的高度不止44,原因是因为那是导航控制器的背景图片
     */
    //给导航控制器的背景图片设置一个空的图片,使其看起来透明.这里不能直接传nil
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    //取出导航控制器的阴影线,也是传一个空图片,使其看起来透明
    [self.navigationController.navigationBar setShadowImage:image];

}
//简介编辑按钮
- (IBAction)editUserInfo:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"BasicView" bundle:nil];
    UIViewController *vc = [sb instantiateInitialViewController];
    vc.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(navback) image:@"navigationbar_back" heighlightImage:@"navigationbar_back_highlighted"];
    SIXNavigationController *nav = [[SIXNavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)navback{
    SIXLog(@"返回");
    [self dismissViewControllerAnimated:YES completion:nil];


}


@end
